package com.zhaojonhy.zhaopangwb.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.view.View.OnClickListener ;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.StatusesAPI;
import com.sina.weibo.sdk.openapi.UsersAPI;
import com.zhaojonhy.zhaopangwb.Fragment.FragmentController;
import com.zhaojonhy.zhaopangwb.Fragment.FragmentControllerForInfo;
import com.zhaojonhy.zhaopangwb.R;
import com.zhaojonhy.zhaopangwb.adapter.StatusAdapter;
import com.zhaojonhy.zhaopangwb.bean.StatusesFriendsTimeline;
import com.zhaojonhy.zhaopangwb.bean.User;
import com.zhaojonhy.zhaopangwb.bean.Statuses;
import com.zhaojonhy.zhaopangwb.utils.AccessTokenKeeper;
import com.zhaojonhy.zhaopangwb.utils.BaseApplication;
import com.zhaojonhy.zhaopangwb.utils.Constants;
import com.zhaojonhy.zhaopangwb.utils.ImageOptHelper;
import com.zhaojonhy.zhaopangwb.utils.TitleBuilder;
import com.zhaojonhy.zhaopangwb.widget.Pull2RefreshListView;
import com.zhaojonhy.zhaopangwb.widget.UnderlineIndicatorView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/10/15.
 */

public class UserInfoActivity extends FragmentActivity implements OnClickListener ,OnCheckedChangeListener {

    private static final String TAG = UserInfoActivity.class.getSimpleName() ;
    private ImageLoader imageLoader ;
    private UsersAPI mUsersAPI;
    private Oauth2AccessToken mAccessToken;
    private StatusesAPI statusesAPI ;
    // 标题栏
    private View title;
    private ImageView titlebar_iv_left;
    private TextView titlebar_tv;
    // headerView - 用户信息
    private View user_info_head;
    private ImageView iv_avatar;
    private TextView tv_name;
    private TextView tv_friends;
    private TextView tv_follows;
    private TextView tv_sign;
    // shadow_tab - 顶部悬浮的菜单栏
    private View shadow_user_info_tab;
    private RadioGroup shadow_rg_user_info;
    private UnderlineIndicatorView shadow_uliv_user_info;
    // headerView - 添加至列表中作为header的菜单栏
    private View user_info_tab;
    private RadioGroup rg_user_info;
    private UnderlineIndicatorView uliv_user_info;

    //菜单栏的fragment
    private View fragment_view ;
    private FrameLayout frame_info ;

    private ImageView iv_user_info_head;
    private Pull2RefreshListView plv_user_info;
    private View footView;

    // 用户相关信息
    private boolean isCurrentUser;
    private User user;
    private String userName ;
    private BaseApplication application ;
    // 个人微博列表
    private List<Statuses> statuses = new ArrayList<Statuses>();
    private StatusAdapter statusAdapter;
    // 显示当前已加载至的页数
    private int curPage = 1;
    // 背景图片最小高度
    private int minImageHeight = -1;
    // 背景图片最大高度
    private int maxImageHeight = -1;

    private int curScrollY;

    private int RBCurrentIndex ;
    private FragmentControllerForInfo controller ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);

        mAccessToken = AccessTokenKeeper.readAccessToken(this) ;
        mUsersAPI = new UsersAPI(this, Constants.APP_KEY, mAccessToken) ;
//        statusesAPI = new StatusesAPI(this, Constants.APP_KEY, mAccessToken) ;

        imageLoader = ImageLoader.getInstance() ;
        userName = getIntent().getStringExtra("userName") ;

        if( TextUtils.isEmpty(userName) ){
            //进行非空判断 如果为空就是当前的用户传入
            //记录当前的用户判断和在application中存的user
            isCurrentUser = true ;
            application = (BaseApplication) getApplication();
            user = application.currentUser ;
        }

        initView() ;
        loadData() ;

    }

    private void initView() {

        title = new TitleBuilder(this)
                .setTitleBgRes(R.drawable.userinfo_navigationbar_back)
                .setLeftImage(R.drawable.navigationbar_back_sel)
                .setLeftOnClickListener(this)
                .build();

        // 获取标题栏信息,需要时进行修改
        titlebar_iv_left = (ImageView) title.findViewById(R.id.titleBarIvLeft);
        titlebar_tv = (TextView) title.findViewById(R.id.titleBarTv);

        initInfoHead();
        initTab();
        initListView();

    }

    // 初始化用户信息
    private void initInfoHead() {
        iv_user_info_head = (ImageView) findViewById(R.id.iv_user_info_head) ;
        user_info_head = View.inflate(this,R.layout.user_info_head,null) ;
        iv_avatar = (ImageView)user_info_head.findViewById(R.id.iv_avatar) ;
        tv_name = (TextView) user_info_head.findViewById(R.id.tv_name) ;
        tv_friends = (TextView) user_info_head.findViewById(R.id.tv_friends) ;
        tv_follows = (TextView) user_info_head.findViewById(R.id.tv_follows) ;
        tv_sign = (TextView) user_info_head.findViewById(R.id.tv_sign) ;

    }

    //初始化菜单栏
    private void initTab() {
// 悬浮显示的菜单栏
        shadow_user_info_tab = findViewById(R.id.user_info_tab);
        shadow_rg_user_info = (RadioGroup) findViewById(R.id.rg_user_info);
        shadow_uliv_user_info = (UnderlineIndicatorView) findViewById(R.id.uliv_user_info);

        shadow_rg_user_info.setOnCheckedChangeListener(this);
        shadow_uliv_user_info.setCurrentItemWithoutAnim(1);

        // 添加到列表中的菜单栏
        user_info_tab = View.inflate(this, R.layout.user_info_tab, null);
        rg_user_info = (RadioGroup) user_info_tab.findViewById(R.id.rg_user_info);
        uliv_user_info = (UnderlineIndicatorView) user_info_tab.findViewById(R.id.uliv_user_info);

        rg_user_info.setOnCheckedChangeListener(this);
        uliv_user_info.setCurrentItemWithoutAnim(1);
    }

    //初始化切换页面
    private void initFragmentView (){
        fragment_view = View.inflate(this,R.layout.frag_info,null) ;
        frame_info = (FrameLayout)fragment_view.findViewById(R.id.frame_info) ;
    }
    @SuppressLint("NewApi")
    private void initListView() {
        plv_user_info = (Pull2RefreshListView)findViewById(R.id.plv_user_info) ;
        initLoadingLayout();
        footView = View.inflate(this , R.layout.footview_loading , null) ;
        // addHeadView 是listView里面的方法，所以必须转成listView
        final ListView lv = plv_user_info.getRefreshableView() ;
        statusAdapter = new StatusAdapter(this, statuses);
        plv_user_info.setAdapter(statusAdapter);
        lv.addHeaderView(user_info_head);
        lv.addHeaderView(user_info_tab);

//        initFragmentView() ;
//        lv.addHeaderView(frame_info);

        controller = new FragmentControllerForInfo(this,R.id.frame_info) ;
        controller.showFragment(1);
//
//        plv_user_info.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
//            @Override
//            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
//                loadStatuses(1) ;
//            }
//        });
//        plv_user_info.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
//            @Override
//            public void onLastItemVisible() {
//                loadStatuses( curPage + 1 ) ;
//            }
//        });
        plv_user_info.setOnScrollListener(new AbsListView.OnScrollListener() { //监听滚动事件
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                //这时候的高度根据列表中的top获取，当列表向上滚动，整个控件向上滚动，它的top就相当于一个scrollY
                iv_user_info_head.layout(0,user_info_head.getTop(),
                        iv_user_info_head.getWidth(),
                        user_info_head.getTop() + iv_user_info_head.getHeight());

                //监听滚动事件，当菜单栏的底部位置小于标题栏的底部位置时显示隐藏的菜单栏
                if( user_info_head.getBottom() < title.getBottom() ){
                    shadow_user_info_tab.setVisibility(View.VISIBLE);
                    title.setBackgroundResource(R.drawable.navigationbar_background);
                    titlebar_iv_left.setImageResource(R.drawable.navigationbar_back_sel);
                    titlebar_tv.setVisibility(View.VISIBLE);
                }else {
                    shadow_user_info_tab.setVisibility(View.GONE);
                    title.setBackgroundResource(R.drawable.userinfo_navigationbar_background);
                    titlebar_iv_left.setImageResource(R.drawable.userinfo_navigationbar_back_sel);
                    titlebar_tv.setVisibility(View.GONE);
                }

            }
        });

        // 设置滚动监听（先前setOnScrollListener）是针对列表部分，自定义一个监听是整体部分
        plv_user_info.setOnP2RefreshChangeScrollListener(new Pull2RefreshListView.onPlvScrollListener() {
            @Override
            public void onScrollChanged(int l, int t, int oldl, int oldt) {

                // 高度希望是根据滚动的位置进行增加的，先获取 y 轴方向的滚动距离
                int scrollY = curScrollY = t ;
               //  自带的onScrollChanged监听了滚动状态，但是没有提供回调，这时候我们做一个回调接口暴露出来
                //  在布局中的图片显示ScaleType="centerCrop" ,多余部分会剪裁，
                //  思路就是当下拉时把高度设置(lauout_height)变高，直到显示整张图片时，完成刷新
                if(minImageHeight == -1){
                    //初始化onCreate的时候整个视图还没绘制完成所以获取的整个宽高都是0，所以放在监听中
                    minImageHeight = iv_user_info_head.getHeight() ;
                }

                if(maxImageHeight == -1) {
                    // 可以直接获取图片的高度
                    // Rect位于android.graphics下，表示一个矩形，由四条边的坐标组成
                    Rect rect = iv_user_info_head.getDrawable().getBounds() ;
                    maxImageHeight = rect.bottom - rect.top ;
                }

                //layout()方法可以让控件重新规定它的位置，包括它的size大小
                //当向下拉动的时候，视图是往上滚动的，是往负轴移动的，所以减法，再加上判断
                if(minImageHeight - scrollY < maxImageHeight){
                    iv_user_info_head.layout(0,0,iv_user_info_head.getWidth(),
                            minImageHeight - scrollY);
                }else {
                    // 这时候已经显示完全，所以图片跟着滚动下拉，
                    // 顶部的移动距离scrollY已经移动了要排除之前滚动的距离（最大-最小）
                    // 底部的位置就是移动的距离+视图的高
                    iv_user_info_head.layout(0,-scrollY - (maxImageHeight - minImageHeight) ,
                            iv_user_info_head.getWidth(),
                            -scrollY - (maxImageHeight - minImageHeight) + iv_user_info_head.getHeight());
                }
                // 如果希望向上拉动，图片跟着向上，这时候是listView的监听了。
                // 要在listView（setOnScrollListener）里面设置
            }
        });

        // 整体的下拉控件自带的滚动效果有问题，监听layoutChange事件，
        // 当前的滚动状态和实际布局的状态不符，让它保持原来的效果
        iv_user_info_head.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if(curScrollY == bottom - oldBottom ){
                    iv_user_info_head.layout(0, 0,
                            iv_user_info_head.getWidth(),
                            oldBottom);
                }
            }
        });
    }

    private void initLoadingLayout() {
        ILoadingLayout loadingLayout = plv_user_info.getLoadingLayoutProxy() ; // 下拉刷新的样式
        loadingLayout.setPullLabel(""); // 下拉时候的文字
        loadingLayout.setRefreshingLabel(""); //  正在刷新时候的文字
        loadingLayout.setReleaseLabel(""); // 释放后的文字
        loadingLayout.setLoadingDrawable(new ColorDrawable(getResources().getColor(R.color.transparent)));
    }

//    private void loadStatuses(final int requestPage) {
//
//
//        Log.d(TAG,"user.getId()-->"+"userName: "+userName);
//        if( user != null){
//            Log.d(TAG,"user.getId()-->"+"user.getId(): "+user.getId());
//        }
//
//        statusesAPI.userTimeline(
//                user == null ? -1 : user.getId(),
//                userName,
//                0, 0, 50, requestPage, false, 0, false,
//                new RequestListener() {
//                    @Override
//                    public void onComplete(String response) {
//                        Log.d(TAG,"user.getId()-->"+"response: "+response);
//                        Log.d(TAG,"userTimeline.getTotal_number():"+"loadStatuses1: "+
//                                new Gson().fromJson(response,StatusesFriendsTimeline.class).getStatuses());
//                        if( requestPage == 1 ){
//                            statuses.clear();
//                        }
//
//                        addStatus(new Gson().fromJson(response,StatusesFriendsTimeline.class)) ;
//                        Log.d(TAG,"userTimeline.getTotal_number():"+"loadStatuses2: "+
//                                new Gson().fromJson(response,StatusesFriendsTimeline.class).getStatuses());
//                    }
//
//                    @Override
//                    public void onWeiboException(WeiboException e) {
//                        Log.d(TAG,"user.getId()-->"+"response: "+"faile");
//                    }
//                });
//    }

    private void loadData() {
        if(isCurrentUser){
            //如果是当前授权用户，直接设置信息*
            setUserInfo() ;
        }else {
            //如果是查看他人，调用获取用户信息接口
            loadUserInfo() ;
        }
        // 加载用户所属微博列表
//        loadStatuses(1);
    }

    private void setUserInfo() {
        if( user == null ){
            return ;
        }
        imageLoader.displayImage(user.getAvatar_large(),new ImageViewAware(iv_avatar), ImageOptHelper.getAvatarOptions()) ;
        tv_name.setText(user.getName());
        titlebar_tv.setText(user.getName());
        tv_friends.setText("关注 " + user.getFriends_count());
        tv_follows.setText("粉丝 " + user.getFollowers_count());
        tv_sign.setText("简介:" + user.getDescription());
    }

    private void loadUserInfo() {
        mUsersAPI.show(userName, new RequestListener() {
            @Override
            public void onComplete(String response) {
                // 获取用户信息并设置
                user = new Gson().fromJson(response,
                        User.class);
                setUserInfo();
            }

            @Override
            public void onWeiboException(WeiboException e) {

            }
        });
    }

    private void addStatus(StatusesFriendsTimeline userTimeline){ //添加数据
        Log.d("调用了吗？？","addData") ;
        for (Statuses status : userTimeline.getStatuses()){
            //接口 List<E>containsboolean contains(Object o)如果列表包含指定的元素，则返回 true。
            // 更确切地讲，当且仅当列表包含满足 (o==null ? e==null : o.equals(e)) 的元素 e 时才返回 true。
            if( !statuses.contains(status)){ //list.contains(Bean) ,防止数据的重复添加
                statuses.add(status) ; //数据添加到集合中
            }
        }

        //可能要开线程
        statusAdapter.notifyDataSetChanged();//适配器更新
        plv_user_info.onRefreshComplete();


        Log.d(TAG,"userTimeline.getTotal_number():"+userTimeline.getTotal_number()) ;
        if (curPage < userTimeline.getTotal_number()) { //判断是否继续加载 ,当前页小于总页数
            addFootView(plv_user_info, footView) ; //继续加载
        }else {
            removeFootView(plv_user_info, footView) ; //移除加载
        }
    }

    private void addFootView(PullToRefreshListView plvHome, View footView ) {
        ListView lv = plvHome.getRefreshableView();
        if(lv.getFooterViewsCount() == 1) {
            lv.addFooterView(footView);
        }
    }

    private void removeFootView(PullToRefreshListView plvHome, View footView) {
        ListView lv = plvHome.getRefreshableView();
        Log.d(TAG,"lv.getFooterViewsCount()"+ lv.getFooterViewsCount()) ;
        if(lv.getFooterViewsCount() > 1) {
            lv.removeFooterView(footView);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.titleBarIvLeft :
                finish();
                break;
            default:
                break;
        }
    }

    private void syncRadioButton(RadioGroup group, int checkedId){
        //获取RadioGroup中被选中的RadioButton的下标
        int index = group.indexOfChild(group.findViewById(checkedId)) ;
        if(shadow_user_info_tab.getVisibility() == View.VISIBLE) { //显示
            //隐藏菜单栏显示有动画的效果
            shadow_uliv_user_info.setCurrentItem(index);
            ( (RadioButton)rg_user_info.findViewById(checkedId) ).setChecked(true);
            uliv_user_info.setCurrentItemWithoutAnim(index);

        } else {
            //隐藏菜单栏显示没有动画的效果，列表的菜单栏有动画效果
            uliv_user_info.setCurrentItem(index);
            ( (RadioButton)shadow_rg_user_info.findViewById(checkedId) ).setChecked(true);
            shadow_uliv_user_info.setCurrentItemWithoutAnim(index);

        }

        switch (checkedId) {
            case R.id.rb_info:
                controller.showFragment(0);
                break;
            case R.id.rb_status:
                controller.showFragment(1);
                break;
            case R.id. rb_photos:
                controller.showFragment(2);
                break;
            case R.id.rb_manager:
                controller.showFragment(3);
                break;

            default:
                break;
        }

    }
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        //根据按键的选中状态来视图，由于RadioButton太多,方法类似，因此提取一个RadioButton的函数
        syncRadioButton(group, checkedId) ;
//        switch (checkedId) {
//		case R.id.rb_info:
//			if(shadow_user_info_tab.getVisibility() == View.VISIBLE) {
//                RadioButton rb_info = (RadioButton)rg_user_info.findViewById(R.id.rb_info) ;
//				rb_info.setChecked(true);
//				uliv_user_info.setCurrentItemWithoutAnim(0);
//
//                RadioButton shadow_rb_info = (RadioButton)shadow_user_info_tab.findViewById(R.id.rb_info) ;
//                shadow_rb_info.setChecked(true);
//				shadow_uliv_user_info.setCurrentItem(0);
//			} else {
//                RadioButton rb_info = (RadioButton)rg_user_info.findViewById(R.id.rb_info) ;
//                rb_info.setChecked(true);
//				uliv_user_info.setCurrentItem(0);
//
//                RadioButton shadow_rb_info = (RadioButton)shadow_user_info_tab.findViewById(R.id.rb_info) ;
//                shadow_rb_info.setChecked(true);
//				shadow_uliv_user_info.setCurrentItemWithoutAnim(0);
//			}
//			break;
//		case R.id.rb_status:
//			if(shadow_user_info_tab.getVisibility() == View.VISIBLE) {
//                RadioButton rb_status = (RadioButton)rg_user_info.findViewById(R.id.rb_status) ;
//                rb_status.setChecked(true);
//				uliv_user_info.setCurrentItemWithoutAnim(1);
//
//                RadioButton shadow_rb_status = (RadioButton)shadow_user_info_tab.findViewById(R.id.rb_status) ;
//				shadow_rb_status.setChecked(true);
//				shadow_uliv_user_info.setCurrentItem(1);
//			} else {
//                RadioButton rb_status = (RadioButton)rg_user_info.findViewById(R.id.rb_status) ;
//                rb_status.setChecked(true);
//				uliv_user_info.setCurrentItem(1);
//
//                RadioButton shadow_rb_status = (RadioButton)shadow_user_info_tab.findViewById(R.id.rb_status) ;
//				shadow_rb_status.setChecked(true);
//				shadow_uliv_user_info.setCurrentItemWithoutAnim(1);
//			}
//			break;
//		case R.id. rb_photos:
//			if(shadow_user_info_tab.getVisibility() == View.VISIBLE) {
//                RadioButton rb_photos = (RadioButton)rg_user_info.findViewById(R.id.rb_photos) ;
//				rb_photos.setChecked(true);
//				uliv_user_info.setCurrentItemWithoutAnim(2);
//
//                RadioButton shadow_rb_photos = (RadioButton)shadow_user_info_tab.findViewById(R.id.rb_photos) ;
//				shadow_rb_photos.setChecked(true);
//				shadow_uliv_user_info.setCurrentItem(2);
//			} else {
//                RadioButton rb_photos = (RadioButton)rg_user_info.findViewById(R.id.rb_photos) ;
//				rb_photos.setChecked(true);
//				uliv_user_info.setCurrentItem(2);
//
//                RadioButton shadow_rb_photos = (RadioButton)shadow_user_info_tab.findViewById(R.id.rb_photos) ;
//				shadow_rb_photos.setChecked(true);
//				shadow_uliv_user_info.setCurrentItemWithoutAnim(2);
//			}
//			break;
//		case R.id.rb_manager:
//			if(shadow_user_info_tab.getVisibility() == View.VISIBLE) {
//                RadioButton rb_manager = (RadioButton)rg_user_info.findViewById(R.id.rb_manager) ;
//                rb_manager.setChecked(true);
//				uliv_user_info.setCurrentItemWithoutAnim(3);
//
//                RadioButton shadow_rb_manager = (RadioButton)shadow_user_info_tab.findViewById(R.id.rb_manager) ;
//				shadow_rb_manager.setChecked(true);
//				shadow_uliv_user_info.setCurrentItem(3);
//			} else {
//                RadioButton rb_manager = (RadioButton)rg_user_info.findViewById(R.id.rb_manager) ;
//                rb_manager.setChecked(true);
//				uliv_user_info.setCurrentItem(3);
//
//                RadioButton shadow_rb_manager = (RadioButton)shadow_user_info_tab.findViewById(R.id.rb_manager) ;
//                shadow_rb_manager.setChecked(true);
//				shadow_uliv_user_info.setCurrentItemWithoutAnim(3);
//			}
//			break;
//
//		default:
//			break;
//		}
    }
}
